package com.itheima.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.pojo.Result;
import com.itheima.utils.JwtUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Author: Zheng
 * Date:   2024/1/27  10:18
 * Package：com.itheima.interceptor
 * Description：
 * Version：1.0
 */
@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("preHandle方法触发了。。。。。。。。。。");

        String uri = request.getRequestURI();
        log.info("拦截到路径,{}", uri);

        String token = request.getHeader("token");
        log.info("获取token：{}",token);
        if (token == null) {
            log.info("令牌不存在，不放行");
            Result notLogin = Result.error("NOT_LOGIN");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(notLogin));
            return false;
        }

        try {
            JwtUtils.parseJWT(token);
            log.info("解析token：{}",token);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("令牌失效或者过期~。。。");
            Result notLogin = Result.error("NOT_LOGIN");
            response.setContentType("application/json;charset=utf-8");
            response.getWriter().write(JSON.toJSONString(notLogin));
            return false;

        }
        log.info("令牌合法，放行。。。。。");
        return true;
    }
}
